package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.entity.Result;
import com.zt.pojo.*;
import com.zt.pojo.request.BookingRequest;
import com.zt.service.*;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 预约控制器
 */
@RestController
public class BookingController {

    @Autowired
    private BookingsService bookingsService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private TeachersService teachersService;

    @Autowired
    private TeacherRatingService teacherRatingService;

    @Autowired
    private TeacherCertificationService teacherCertificationService;

    /**
     * 创建预约
     * @param request 预约请求数据
     * @return 预约结果
     */
    @PostMapping({"/bookings","/bookings/submit"}) //todo 预约
    //,
    // @RequestAttribute(value = "userId", required = false) Integer userId
    public Result createBooking(@RequestBody BookingRequest request) {
        try {
            // 验证请求体不为空
            if (request == null) {
                return Result.error("预约请求数据不能为空");
            }
            
            System.out.println("接收到创建预约请求，数据: " + request);
            
            // 如果没有获取到用户ID，使用默认值1
            Integer userId = request.getUserId();
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }
            
            // 调用服务创建预约
            Integer bookingId = bookingsService.createBooking(request, userId);
            
            return Result.success("预约创建成功", bookingId);
        } catch (HttpMessageNotReadableException e) {
            // 请求体JSON解析错误
            System.out.println("请求体JSON解析错误: " + e.getMessage());
            e.printStackTrace();
            return Result.error("请求数据格式错误: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            // 参数验证错误
            System.out.println("参数验证错误: " + e.getMessage());
            e.printStackTrace();
            return Result.error(e.getMessage());
        } catch (Exception e) {
            System.out.println("预约创建异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("预约创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户预约列表
     * @return 预约列表
     * 根据用户id 获取 预约列表
     */
    @GetMapping("/bookings")
    public Result getUserBookings(@RequestParam(value = "id") Integer userId) {
        try {
            // 如果没有获取到用户ID，结束
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }
            
            // 获取用户预约列表
            List<Bookings> bookings = bookingsService.getUserBookings(userId);
            for (Bookings booking : bookings) {
                if (booking != null) {
                    // 获取教师评价 - 应该根据booking_id查询，而不是直接用booking.getId()
                    LambdaQueryWrapper<TeacherRating> ratingWrapper = new LambdaQueryWrapper<>();
                    ratingWrapper.eq(TeacherRating::getBookingId, booking.getId());
                    TeacherRating teacherRating = teacherRatingService.getOne(ratingWrapper);

                    booking.setTeacherRating(teacherRating);

                    // 只有当teacherRating不为null时才继续处理
                    if (teacherRating != null) {
                        Integer teacherId = teacherRating.getTeacherId();

                        // 只有当teacherId不为null时才查询教师认证信息
                        if (teacherId != null) {
                            TeacherCertification certification = teacherCertificationService.getOne(
                                new QueryWrapper<TeacherCertification>().eq("teacher_id", teacherId)
                            );

                            if (certification != null) {
                                // 清除敏感信息
                                certification.setIdNumber(null);
                                certification.setIdCardBack(null);
                                certification.setIdCardFront(null);
                                certification.setTeacherCertImg(null);
                                certification.setDiplomaImg(null);
                                booking.setTeacherCertification(certification);
                            }
                        }
                    }
                }
            }
       /*     for (Bookings booking : bookings) {
                if (booking.getKc()==null || booking.getKc().isEmpty()){
                    Integer bookingId = booking.getId();
                    // 根据booking id 获取课程名称
                    Order order = ordersService.getOne(new QueryWrapper<Order>().eq("booking_id", bookingId));
                    System.out.println("获取到课程名称"+order.getCourseName());
                    booking.setKc(order.getCourseName());
                }
            }*/
            return Result.success("获取预约列表成功", bookings);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取预约列表失败: " + e.getMessage());
        }
    }


    /**
     * 获取用户预约列表（按状态过滤）
     * @param status 状态：0-待支付，1-已支付，2-已取消，不传则返回所有状态
     * @return 预约列表
     */
    @GetMapping("/bookings/status")
    public Result getUserBookingsByStatus(
        @RequestParam(value = "status", required = false) Integer status,
        @RequestAttribute(value = "userId", required = false) Integer userId) {
        try {
            // 如果没有获取到用户ID，使用默认值1
            if (userId == null) {
                userId = 1;
            }
            
            // 获取用户预约列表
            List<Bookings> bookings = bookingsService.getUserBookingsByStatus(userId, status);
            
            return Result.success("获取预约列表成功", bookings);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取预约列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消预约
     * @param id 预约ID
     * @return 取消结果
     */
    @PostMapping("/bookings/{id}/cancel")
    public Result cancelBooking(@PathVariable Integer id, 
                               @RequestAttribute(value = "userId", required = false) Integer userId) {
        try {
            // 如果没有获取到用户ID，使用默认值1
            if (userId == null) {
                userId = 1;
            }
            
            // 调用服务取消预约
            boolean success = bookingsService.cancelBooking(id, userId);
            
            if (success) {
                return Result.success("预约取消成功");
            } else {
                return Result.error("预约取消失败：预约不存在或状态不允许取消");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("预约取消失败: " + e.getMessage());
        }
    }

    /**
     * 根据预约ID获取预约详情
     * @param bookingId 预约ID
     * @return 预约详情
     */
    @GetMapping("/bookings/info")
    public Result getBookingInfo(@RequestParam("id") Integer bookingId) {
        try {
            // 调用服务获取预约详情
            Bookings booking = bookingsService.getById(bookingId);

            if (booking == null) {
                return Result.error("预约不存在");
            }
            QueryWrapper<Order> orderQueryWrapper =new QueryWrapper<>();
            orderQueryWrapper.eq("booking_id",bookingId);
            orderQueryWrapper.eq("status",3);
            Order order = ordersService.getOne(orderQueryWrapper);
            if (order==null){
                return Result.error("未找到订单或者订单未支付");
            }
            booking.setOrder(order);

            QueryWrapper<Teachers> teachersQueryWrapper =new QueryWrapper<>();
            teachersQueryWrapper.eq("id",order.getTeacherId());
            Teachers teachers = teachersService.getOne(teachersQueryWrapper);
            if (teachers==null){
                return Result.success("获取预约详情成功", booking);
            }
            booking.setTeachers(teachers);


            return Result.success("获取预约详情成功", booking);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取预约详情失败: " + e.getMessage());
        }
    }

    /**
     * 手动更新预约状态
     * @param id 预约ID
     * @param status 新状态
     * @return 更新结果
     */
    @PostMapping("/bookings/{id}/status/{status}")
    public Result updateBookingStatus(@PathVariable Integer id, @PathVariable Integer status) {
        try {
            boolean success = bookingsService.updateBookingStatus(id, status);
            
            if (success) {
                return Result.success("预约状态更新成功");
            } else {
                return Result.error("预约状态更新失败：预约不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("预约状态更新失败: " + e.getMessage());
        }
    }
}
